import json
import re
import os

TAB_PREFIX = "t_"

p = re.compile(r'(?P<folder>(%s))(?P<tablename>\w+)' % TAB_PREFIX)


def getRealTableName(m):
    d = m.groupdict()
    return d['tablename']


def getTableName(table_name):
    return p.sub(getRealTableName, table_name)


def snake_to_camel_case(text):
    components = text.split('_')
    return ''.join(x.title() for x in components[0:])


def write_file(file_name, obj):
    fileFullName = "D:\ETL\gin-admin-module-yaml\yamls\%s.yaml" % file_name
    delete_file(fileFullName)
    print("gen:%s" % fileFullName)
    with open(fileFullName, 'w') as file_object:
        file_object.write("name: %s\n" % obj.name)
        file_object.write("comment: %s\n" % obj.comment)
        file_object.write("fields:\n")
        for field in obj.fields:
            file_object.write("  - name: %s\n" % field.name)
            file_object.write("    type: %s\n" % field.type)
            file_object.write("    comment: %s\n" % field.comment)
            file_object.write("    required: %s\n" % ("true" if field.require else "false"))
            file_object.write("    binding_options: \"%s\"\n" % field.binding_options)
            file_object.write("    gorm_options: \"%s\"\n" % field.gorm_options)


def delete_file(fileFullName):
    if os.path.exists(fileFullName):
        os.remove(fileFullName)
        #os.unlink(path)
    # else:
    #     print('no such file:%s' % fileFullName)


def extDictFromJson(jsonStr):
    dic = json.loads(jsonStr)
    return dic


def insertTarget(tgCursor, sql):
    try:
        tgCursor.execute(sql)
        # tgDb.commit()
    except Exception as e:
        # tgDb.rollback()
        print("Error: unable to fecth data:" + str(e))
